package com.immediatus.engine.text;


import com.immediatus.graphics.camera.Camera;
import com.immediatus.graphics.font.Font;
import com.immediatus.graphics.vertex.TextVertexBuffer;
import com.immediatus.options.Align;

import javax.microedition.khronos.opengles.GL10;

public class ChangeableTextLabel extends TextLabel{
    private static final String ELLIPSIS = "...";
    private static final int ELLIPSIS_CHARACTER_COUNT = ELLIPSIS.length();

    private int _count;

    public ChangeableTextLabel(final float x_, final float y_, final Font font_, final String text_){
        this(x_, y_, font_, text_, text_.length() - countOccurrences(text_, '\n'));
    }

    public ChangeableTextLabel(final float x_, final float y_, final Font font_, final String text_, final int charactersMaximum_){
        this(x_, y_, font_, text_, Align.LEFT, charactersMaximum_);
    }

    public ChangeableTextLabel(final float x_, final float y_, final Font font_, final String text_, final Align align_, final int charactersMaximum_){
        super(x_, y_, font_, text_, align_, charactersMaximum_);
        this._count = text_.length() - countOccurrences(text_, '\n');
    }

    public void setText(final String text_){
        this.setText(text_, false);
    }

    public void setText(final String text_, final boolean ellipsis_){
        final int textCharacterCount = text_.length() - countOccurrences(text_, '\n');
        if (textCharacterCount > this.getCharactersMaximum()){
            if (ellipsis_ && this.getCharactersMaximum() > ELLIPSIS_CHARACTER_COUNT){
                this.updateText(text_.substring(0,
                        this.getCharactersMaximum ()- ELLIPSIS_CHARACTER_COUNT).concat(ELLIPSIS));
            } else{
                this.updateText(text_.substring(0, this.getCharactersMaximum()));
            }
            this._count = this.getCharactersMaximum();
        } else{
            this.updateText(text_);
            this._count = textCharacterCount;
        }
    }

    @Override
    protected void drawVertices(final GL10 gl_, final Camera camera_){
        gl_.glDrawArrays(GL10.GL_TRIANGLES, 0,
                this._count * TextVertexBuffer.VERTICES_PER_CHARACTER);
    }
}
